<template>
  <a-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    v-drag
  >
    <template slot="footer">
      <a-button @click="handleCancel">{{$t('关闭')}}</a-button>
    </template>
    <a-card :bordered="false">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-col :xl="10" :lg="11" :md="12" :sm="24">
              <a-form-item :label="$t('业务时间')">
                <j-date
                  :show-time="true"
                  date-format="YYYY-MM-DD HH:mm:ss"
                  :placeholder="$t('请选择开始时间')"
                  class="query-group-cust"
                  v-model="queryParam.buyTime_begin"
                ></j-date>
                <span>~</span>
                <j-date
                  :show-time="true"
                  date-format="YYYY-MM-DD HH:mm:ss"
                  :placeholder="$t('请选择结束时间')"
                  class="query-group-cust"
                  v-model="queryParam.buyTime_end"
                ></j-date>
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('商品分类')">
                <a-tree-select
                  style="width: 100%"
                  :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="treeData"
                  :search-placeholder="$t('请选择')"
                  v-model="queryParam.goodsKindId"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('商品名称')">
                <a-input :placeholder="$t('请输入商品名称')" v-model="queryParam.goodsName"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('业务渠道')">
                <a-select v-model="queryParam.deviceType">
                  <a-select-option :value="item.value" :key="index" v-for="(item, index) in deviceinfoList">{{
                    item.title
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('操作员')">
                <a-select v-model="queryParam.createBy">
                  <a-select-option :value="item.id" :key="index" v-for="(item, index) in userList">{{
                    item.realname
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('订单号')">
                <a-input :placeholder="$t('请输入订单号')" v-model="queryParam.id"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('会员信息')">
                <a-input :placeholder="$t('请输入手机号/卡号/姓名')" v-model="queryParam.memberInfoSearch"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="4" :lg="6" :md="7" :sm="24">
              <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery">{{$t('查询')}}</a-button>
                <a-button type="primary" @click="searchReset" style="margin-left: 8px">{{$t('重置')}}</a-button>
                <a-button type="primary" @click="handleExportXls($t('活动记录'))" style="margin-left: 8px">{{$t('导出')}}</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 查询区域-END -->

      <!-- table区域-begin -->
      <div>
        <a-table
          ref="table"
          size="middle"
          :scroll="{ x: true }"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          class="j-table-force-nowrap"
          @change="handleTableChange"
        >
          <template slot="footer">
            <div>
              <span>{{$t('数量')}}：{{ total.amount }}</span
              ><span style="margin-left: 10px">{{$t('金额')}}：{{ total.payAmount.toFixed(2) }}</span>
            </div>
          </template>
        </a-table>
      </div>
    </a-card>
  </a-modal>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { initDictOptions, filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import { getAction, downFile } from '@/api/manage'

export default {
  name: 'ActivityRecordsModal',
  mixins: [mixinDevice],
  components: {},
  data() {
    return {
      description: '活动记录',
      queryParam: {
        column: 'createTime',
        order: 'desc',
        buyTime_begin: '',
        buyTime_end: '',
        goodsKindId: '',
        goodsName: '',
        deviceType: '',
        createBy: '',
        orderId: '',
        memberInfoSearch: '',
      },
      // 表头
      columns: [
        {
          title: this.$t('订单号'),
          align: 'center',
          dataIndex: 'id',
        },
        {
          title: this.$t('购买时间'),
          align: 'center',
          dataIndex: 'buyTime',
        },
        {
          title: this.$t('商品名称'),
          align: 'center',
          dataIndex: 'goodsName',
        },
        {
          title: this.$t('数量'),
          align: 'center',
          dataIndex: 'amount',
          customCell: (text, record) => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('商品分类'),
          align: 'center',
          dataIndex: 'goodsKindName',
        },
        {
          title: this.$t('金额'),
          align: 'center',
          dataIndex: 'payAmount',
          customRender: (text, record) => {
            return text.toFixed(2)
          },
          customCell: (text, record) => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('手机号'),
          align: 'center',
          dataIndex: 'memberPhone',
        },
        {
          title: this.$t('会员卡号'),
          align: 'center',
          dataIndex: 'cardSn',
        },
        {
          title: this.$t('姓名'),
          align: 'center',
          dataIndex: 'memberName',
        },
        {
          title: this.$t('业务渠道'),
          align: 'center',
          dataIndex: 'deviceType_dictText',
        },
        {
          title: this.$t('操作员'),
          align: 'center',
          dataIndex: 'createBy',
        },
      ],
      url: {
        list: '/ordergoods/bisOrderGoods/list',
        exportXlsUrl: '/ordergoods/bisOrderGoods/exportXlsByActivity',
      },
      dictOptions: {},
      userList: [],
      title: this.$t('活动记录'),
      width: 1500,
      visible: false,
      confirmLoading: false,
      dataSource: [],
      loading: false,
      ipagination: {
        current: 1,
        pageSize: 30,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + this.$t('sum-total',{total:total})
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
        onShowSizeChange: (current, pageSize) => this.handleSizeChange(current, pageSize),
      },
      treeData: [],
      deviceinfoList: [],
      total: {
        amount: 0,
        payAmount: 0,
      },
      activityId: '',
    }
  },
  created() {},
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    initDictConfig() {
      getAction('/sys/user/list').then((res) => {
        if (res.success) {
          this.userList = res.result.records
          this.userList.unshift({ id: '', realname: this.$t('全部') })
        }
      })
      initDictOptions('bis_device_info.type').then((res) => {
        if (res.success) {
          this.deviceinfoList = res.result
          this.deviceinfoList.unshift({ value: '', title: this.$t('全部') })
        }
      })
    },
    show(record) {
      this.visible = true
      this.activityId = record.id
      this.queryParam.activityId = record.id
      this.loadData(1)
      this.initDictConfig()
      this.select()
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error(this.$t('请设置url.list属性'))
        return
      }
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.queryParam
      params.pageNo = this.ipagination.current;
      params.pageSize = this.ipagination.pageSize;
      this.loading = true
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records
            this.getTotal()
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    getTotal() {
      getAction('/ordergoods/bisOrderGoods/total', this.queryParam).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            this.total = res.result.records[0]
          } else {
            this.total.amount = 0
            this.total.payAmount = 0
          }
        }
      })
    },
    searchQuery() {
      this.loadData(1)
    },
    handleCancel() {
      this.visible = false
    },
    searchReset() {
      this.queryParam = {
        column: 'createTime',
        order: 'desc',
        buyTime_begin: '',
        buyTime_end: '',
        goodsKindId: '',
        goodsName: '',
        deviceType: '',
        createBy: '',
        orderId: '',
        memberInfoSearch: '',
        activityId: this.activityId,
      }
      this.loadData(1)
    },
    handleTableChange(pagination, filters, sorter) {
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    handleSizeChange(current, pageSize) {
      this.ipagination.pageSize = pageSize
    },
    select() {
      let that = this
      let param = {}
      param.pageNo = 1
      param.pageSize = 9999
      param.column = 'sort'
      param.order = 'asc'
      getAction('/goods/bisGoodsKind/rootList', param)
        .then((res) => {
          if (res.success) {
            that.allChildKind = []
            if (res.result.records.length > 0) {
              res.result.records.forEach((col) => {
                col.key = '' + col.id
                col.value = '' + col.id
                col.title = '' + col.name
                col.id = '' + col.id
                col.pid = '' + col.pid
                col.hasChild = '' + col.hasChild
                if (col.hasChild != '0') {
                  that.getHasChild(col)
                }
              })
              that.treeData = that.getDataByResult(res.result.records)
              that.treeData.unshift({ key: '', id: '', value: '', title: this.$t('全部') })
            } else {
              that.treeData = []
            }
          } else {
            that.$alert(res.message, this.$t('提示'), {
              confirmButtonText: this.$t('确定'),
              callback: (action) => {},
            })
          }
        })
        .catch((error) => {
          console.log(error)
        })
    },
    getHasChild(record) {
      let that = this
      let query = {}
      query.pageNo = 1
      query.pageSize = 9999
      query.pid = record.id
      getAction('/goods/bisGoodsKind/rootList', query)
        .then((res) => {
          if (res.success) {
            if (res.result.records.length > 0) {
              res.result.records.forEach((col) => {
                col.key = '' + col.id
                col.value = '' + col.id
                col.title = '' + col.name
                col.pid = '' + col.pid
                col.id = '' + col.id
                col.hasChild = '' + col.hasChild
                if (col.hasChild != '0') {
                  that.getHasChild(col)
                }
              })
              record.children = that.getDataByResult(res.result.records)
              that.treeData = [...that.treeData]
            }
          } else {
            that.$message.warning(res.message)
          }
        })
        .catch((error) => {
          console.log(error)
        })
    },
    getDataByResult(result) {
      let that = this
      return result.map((item) => {
        if (item.hasChild == 0 && item.key != '0') {
          that.allChildKind.push(item.key)
        }
        return item
      })
    },
    handleExportXls(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = this.$t('导出文件')
      }
      let param = this.queryParam
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      if (this.isNoPageTotal) {
        param.pageSize = 99999999
      }
      console.log('导出参数', param)
      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning(this.$t('文件下载失败'))
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>